#include "songexporter.h"
#include "list.h"
#include <QFile>
#include <QDir>
#include <QFileInfo>
#include <QDebug>

SongExporter::SongExporter()
{

}

void SongExporter::exportSongs(List<Song*> *songs, QString path)
{
    exportPath = path;
    for(int i=0;i<songs->size();i++){
        songsQueue.enqueue(*songs->get(i));
    }

    start();
}

void SongExporter::run()
{
    QDir dir(exportPath);

    while(songsQueue.size() > 0){
        Song song = songsQueue.dequeue();

        QFile file(song.getFilename());
        if(file.exists()){
            QString artist = song.getArtist();
            QString album = song.getAlbum();
            QString title = song.getTitle();

            fixFolderOrFileName(artist);
            fixFolderOrFileName(album);
            fixFolderOrFileName(title);

            QString partialPath = artist+"/"+album+"/";
            QString filename = title+".mp3";

            dir.mkpath(partialPath); //crear subdirectorios

            file.copy(dir.absoluteFilePath(partialPath+filename));
        }
    }

    quit();
}

void SongExporter::fixFolderOrFileName(QString &text){
    //convertir los caracteres que no son aceptados como nombre de carpetas
    //(\ / : * ? " < > |) a _
    text.replace('\\', '_');
    text.replace('/', '_');
    text.replace(':', '_');
    text.replace('*', '_');
    text.replace('?', '_');
    text.replace('"', '_');
    text.replace('<', '_');
    text.replace('>', '_');
    text.replace('|', '_');

    //window no deja crear carpetas o archivos con . al final
    while(text.endsWith('.')){
        text.remove(text.length()-1, 1);
    }
}
